package com.lbs.jiepiaisi.base;

import android.app.Activity;

import java.util.ArrayList;

/**
 *
 * 时间：2017/6/15 10:24
 * 作用：Activity管理器
 */

public class BaseActivityManager {
    private static ArrayList<Activity> mActivities;
    private static BaseActivityManager instance;
    //单例模式
    public static BaseActivityManager getInstance(){
        if(instance==null){
            instance=new BaseActivityManager();
        }
        return instance;
    }
    /**
     * 取得指定的Activity
     */
    public static ArrayList<Activity>getActivitysByClass(Class<?> cl){
        ArrayList<Activity>temp=new ArrayList<Activity>();
        for(Activity ac:mActivities){
            if(ac.getClass().equals(cl)){
                temp.add(ac);
            }
        }
        return temp;
    }
    /**
     * 取得栈顶的Activity
     */
    public static Activity getActivityByClass(Class<?> cl) {
        ArrayList<Activity> temp = getActivitysByClass(cl);
        return (temp.size() != 0) ? temp.get(temp.size() - 1) : null;
    }
    /**
     * 取得最后添加的Activity
     */
    public static Activity getLastActivity() {
        int size = mActivities == null ? 0 : mActivities.size();
        if (size > 0) {
            return mActivities.get(size - 1);
        } else {
            return null;
        }
    }
    /**
     * 添加一个Activity
     */
    public static void add(Activity activity){
        if(mActivities==null){
            mActivities=new ArrayList<Activity>();
        }
        if(!mActivities.contains(activity)){
            mActivities.add(activity);
        }
    }
    /**
     * 移除一个Activity
     */
    public static void remove(Activity activity){
        if(mActivities!=null){
            mActivities.remove(activity);
        }
    }
    /**
     *  保留当前Activity,删除其他Activity
     */
    public static void finishOtherActivity(Activity activity) {
        if (mActivities != null) {
            ArrayList<Activity> tempList = new ArrayList<Activity>();
            tempList.addAll(mActivities);
            for (Activity other : tempList) {
                if (!other.getClass().equals(activity.getClass())) {
                    other.finish();
                    mActivities.remove(other);
                }
            }
        }
    }
    /**
     * 移除全部Activity
     */
    public static void finishAll(){
        if (mActivities != null) {
            ArrayList<Activity> tempList = new ArrayList<Activity>();
            tempList.addAll(mActivities);
            for (Activity activity : tempList)
                activity.finish();
            mActivities.clear();
        }
    }

}
